/**
* @file         wit_motion_protocol.c
* @author       David Hu (hmd_hubei_cn@163.com)
* @brief        基于维特智能WIT私有协议创建
* @version      1.0
* @date         2023.09.26
* @note         https://wit-motion.yuque.com/wumwnr/ltst03/vl3tpy#O2frB
* @copyright    Copyright (c) 2022 DAVID HU All rights reserved. Licensed under the MIT License (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License in the file LICENSE

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.
**/

#include "wit_motion_protocol.h"

// WIT设备应用协议数据帧解包
bool wit_unpack(uint8_t in_data, wit_packdata_t *out_package) {
  
  if (out_package == NULL) {
    return false;
  }

  if (out_package->data_in_buff == NULL || \
    out_package->data_out_len == NULL ) {
    return false;
  }

  switch (out_package->state) {
    case WIT_HEADER: {
      if (in_data == WIT_PKG_HEADER) {
        out_package->data_in_buff[out_package->package_index++] = in_data;
        out_package->state = WIT_ID;
      }
      break;
    }
    case WIT_ID: {
      if ((in_data == WIT_PKG_ID_ACC_OUT) || \
        (in_data == WIT_PKG_ID_ANGULARVEL_OUT) || \
        (in_data == WIT_PKG_ID_ANGULAR_OUT) || \
        (in_data == WIT_PKG_ID_LON_LAT_OUT) || \
        (in_data == WIT_PKG_ID_GPS_DATA_OUT)) {
        out_package->data_in_buff[out_package->package_index++] = in_data;
        out_package->state = WIT_DATA;
        out_package->package_len = WIT_READ_FRAME_LEN;
      } else {
        out_package->state = WIT_HEADER;
        out_package->package_index = 0;
      }
      break;
    }
    case WIT_DATA: {
      out_package->data_in_buff[out_package->package_index++] = in_data;
      if (out_package->package_index >= out_package->package_len) {
        out_package->state = WIT_HEADER;
        out_package->package_index = 0;
        uint8_t checksum = 0;
        for (int i = 0; i < (out_package->package_len - 1); i++) {
          checksum += out_package->data_in_buff[i];
        }
        if (checksum == out_package->data_in_buff[out_package->package_len - 1]) {
          out_package->data_out_buff = out_package->data_in_buff + 2; // framedata[2] ~ framedata[9]
          out_package->data_id = out_package->data_in_buff[1];
          *out_package->data_out_len = WIT_READ_FRAME_DATAS_LEN;
          return true;
        } else {
          return false;
        }
      }
      break;
    }
  }

  return false;
}



/********************* (C) COPYRIGHT DAVID HU *******END OF FILE ********/
